"""
表计状态管理模块
"""

import time
from typing import Dict, Any, Optional
from datetime import datetime


class MeterState:
    """表计状态类"""
    
    def __init__(self, meter_id: str):
        """
        初始化表计状态
        
        Args:
            meter_id: 表计ID
        """
        self.meter_id = meter_id
        self.current_balance = 0  # 当前余额（分）
        self.total_consumption = 0  # 总用气量（立方米）
        self.transfer_counter = 0  # 传输计数器
        self.last_recharge_time = 0  # 最后充值时间
        self.last_consumption_time = 0  # 最后用气时间
        self.status = "NORMAL"  # 表计状态
        self.alarm_status = "NONE"  # 报警状态
        self.is_active = True  # 表计是否激活
        
        # 历史记录
        self.recharge_history = []
        self.consumption_history = []
        
        # 初始化时间
        self.creation_time = int(time.time())
    
    def add_balance(self, amount: int, token: str) -> Dict[str, Any]:
        """
        增加余额
        
        Args:
            amount: 充值金额（分）
            token: 充值令牌
            
        Returns:
            充值结果
        """
        if amount <= 0:
            return {
                'success': False,
                'error': 'Invalid amount'
            }
        
        # 记录充值历史
        recharge_record = {
            'timestamp': int(time.time()),
            'amount': amount,
            'token': token,
            'previous_balance': self.current_balance,
            'new_balance': self.current_balance + amount
        }
        
        self.recharge_history.append(recharge_record)
        
        # 更新余额
        self.current_balance += amount
        self.last_recharge_time = int(time.time())
        
        return {
            'success': True,
            'amount': amount,
            'previous_balance': recharge_record['previous_balance'],
            'new_balance': self.current_balance,
            'timestamp': self.last_recharge_time
        }
    
    def consume_gas(self, volume: float, rate: float = 2.5) -> Dict[str, Any]:
        """
        消耗燃气
        
        Args:
            volume: 用气量（立方米）
            rate: 气价（元/立方米）
            
        Returns:
            用气结果
        """
        if volume <= 0:
            return {
                'success': False,
                'error': 'Invalid consumption volume'
            }
        
        # 计算费用（转换为分）
        cost_cents = int(volume * rate * 100)
        
        if cost_cents > self.current_balance:
            return {
                'success': False,
                'error': 'Insufficient balance',
                'required': cost_cents,
                'available': self.current_balance
            }
        
        # 记录用气历史
        consumption_record = {
            'timestamp': int(time.time()),
            'volume': volume,
            'cost_cents': cost_cents,
            'previous_balance': self.current_balance,
            'new_balance': self.current_balance - cost_cents
        }
        
        self.consumption_history.append(consumption_record)
        
        # 更新状态
        self.current_balance -= cost_cents
        self.total_consumption += volume
        self.last_consumption_time = int(time.time())
        
        # 检查余额警告
        if self.current_balance < 1000:  # 少于10元
            self.alarm_status = "LOW_BALANCE"
        elif self.current_balance <= 0:
            self.alarm_status = "NO_BALANCE"
            self.status = "DISCONNECTED"
        
        return {
            'success': True,
            'volume': volume,
            'cost_cents': cost_cents,
            'previous_balance': consumption_record['previous_balance'],
            'new_balance': self.current_balance,
            'total_consumption': self.total_consumption,
            'timestamp': self.last_consumption_time
        }
    
    def get_status(self) -> Dict[str, Any]:
        """
        获取表计状态
        
        Returns:
            表计状态信息
        """
        return {
            'meter_id': self.meter_id,
            'current_balance': self.current_balance,
            'current_balance_formatted': f"{self.current_balance / 100:.2f}元",
            'total_consumption': self.total_consumption,
            'transfer_counter': self.transfer_counter,
            'status': self.status,
            'alarm_status': self.alarm_status,
            'is_active': self.is_active,
            'last_recharge_time': self.last_recharge_time,
            'last_consumption_time': self.last_consumption_time,
            'creation_time': self.creation_time
        }
    
    def get_recharge_history(self, limit: int = 10) -> list:
        """
        获取充值历史
        
        Args:
            limit: 返回记录数量限制
            
        Returns:
            充值历史记录
        """
        return self.recharge_history[-limit:] if limit > 0 else self.recharge_history
    
    def get_consumption_history(self, limit: int = 10) -> list:
        """
        获取用气历史
        
        Args:
            limit: 返回记录数量限制
            
        Returns:
            用气历史记录
        """
        return self.consumption_history[-limit:] if limit > 0 else self.consumption_history
    
    def update_transfer_counter(self, new_counter: int) -> bool:
        """
        更新传输计数器
        
        Args:
            new_counter: 新的计数器值
            
        Returns:
            更新是否成功
        """
        if new_counter > self.transfer_counter:
            self.transfer_counter = new_counter
            return True
        return False
    
    def reset_alarm(self) -> None:
        """
        重置报警状态
        """
        self.alarm_status = "NONE"
    
    def set_status(self, status: str) -> None:
        """
        设置表计状态
        
        Args:
            status: 新状态
        """
        valid_statuses = ["NORMAL", "DISCONNECTED", "MAINTENANCE", "ERROR"]
        if status in valid_statuses:
            self.status = status
    
    def get_daily_consumption(self, days: int = 7) -> list:
        """
        获取每日用气量统计
        
        Args:
            days: 统计天数
            
        Returns:
            每日用气量列表
        """
        current_time = int(time.time())
        daily_stats = []
        
        for i in range(days):
            day_start = current_time - (i * 86400)
            day_end = day_start + 86400
            
            # 计算当天的用气量
            day_consumption = sum(
                record['volume'] for record in self.consumption_history
                if day_start <= record['timestamp'] < day_end
            )
            
            daily_stats.append({
                'date': datetime.fromtimestamp(day_start).strftime('%Y-%m-%d'),
                'consumption': day_consumption
            })
        
        return list(reversed(daily_stats))
